// 消息类型定义
export const MessageType = {
  TEXT: 'text',
  CODE: 'code',
  IMAGE: 'image',
  MARKDOWN: 'markdown'
}

// 消息角色定义
export const MessageRole = {
  USER: 'user',
  ASSISTANT: 'assistant',
  SYSTEM: 'system'
}

// 消息格式定义
export class Message {
  constructor({
    id = Date.now().toString(),
    role = MessageRole.USER,
    type = MessageType.TEXT,
    content = '',
    timestamp = Date.now(),
    metadata = {}
  } = {}) {
    this.id = id
    this.role = role
    this.type = type
    this.content = content
    this.timestamp = timestamp
    this.metadata = metadata
  }
}

// AI模型接口适配器基类
export class AIModelAdapter {
  constructor(config = {}) {
    this.config = config
  }

  async sendMessage(message) {
    throw new Error('Method not implemented')
  }

  async init() {
    throw new Error('Method not implemented')
  }

  async destroy() {
    // 清理资源
  }
}

// OpenAI模型适配器
export class OpenAIAdapter extends AIModelAdapter {
  constructor(config) {
    super(config)
    this.apiKey = config.apiKey
    this.apiEndpoint = config.apiEndpoint || 'https://api.openai.com/v1'
    this.modelName = config.modelName || 'gpt-3.5-turbo'
  }

  async sendMessage(message) {
    try {
      if (!this.apiKey) {
        throw new Error('未配置API密钥')
      }

      const response = await fetch(`${this.apiEndpoint}/chat/completions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiKey}`
        },
        body: JSON.stringify({
          model: this.modelName,
          messages: [{
            role: message.role,
            content: message.content
          }],
          temperature: 0.7
        })
      })

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.error?.message || '请求失败')
      }

      const data = await response.json()
      return new Message({
        role: MessageRole.ASSISTANT,
        type: MessageType.TEXT,
        content: data.choices[0]?.message?.content || '无响应内容'
      })
    } catch (error) {
      console.error('OpenAI API调用失败:', error)
      throw error
    }
  }

  async init() {
    // 验证API密钥和端点
    if (!this.apiKey) {
      throw new Error('未配置API密钥')
    }
  }
}

// Claude模型适配器示例
export class ClaudeAdapter extends AIModelAdapter {
  constructor(config) {
    super(config)
  }

  async sendMessage(message) {
    // 实现Claude API调用
    return new Message({
      role: MessageRole.ASSISTANT,
      type: MessageType.TEXT,
      content: '这是Claude的响应'
    })
  }

  async init() {
    // 初始化Claude客户端
  }
}